import React, {useEffect, useState} from "react";
import {useLocation} from 'react-router-dom';
import {Button, Toast, WhiteSpace, List} from "antd-mobile";
import {getDetail} from "../../services/Handle";
import {getDownloadPath, getUnHandle} from "../../services/Result";
import {Brief} from "antd-mobile/es/list/ListItem";

function useQuery() {
    return new URLSearchParams(useLocation().search);
}

const Index = () => {
    const [state, setState] = useState({
        isCorrect: true,
        time: '2020-20-20 11:11:11',
        name: 'test_name',
        unHandle: [],
    });
    const query = useQuery();
    useEffect(() => {
        const fetch = async () => {
            Toast.loading('加载中...');
            let promiseArray;
            try {
                promiseArray = [
                    getDetail(parseInt(query.get('id'), 10), query.get('secretkey')),
                    getUnHandle(parseInt(query.get('id'), 10), query.get('secretkey')),
                ];
                const [detail, list] = await Promise.all(promiseArray);
                const temp = detail.data[0].expiration.split('T');
                const initialState = {
                    isCorrect: true,
                    time: `${temp[0]} ${temp[1].split('+')[0]}`,
                    name: detail.data[0].name,
                    unHandle: list.data,
                };
                setState(() => initialState);
            } catch (e) {
                setState(s => ({ ...s, isCorrect: false }));
            } finally {
                Toast.hide();
            }
        };
        fetch();
    }, []);

    const downloadPackage = async () => {
        Toast.loading('正在生成，请稍后...');
        try {
            const res = await getDownloadPath(parseInt(query.get('id'), 10), query.get('secretkey'));
            res.url = res.url.replace("http://", "https://");
            window.open(res.url);
        } catch (e) {
            Toast.hide();
            Toast.fail(e.message);
        }
        Toast.hide();
    };

    return (
        <div>
            { state.isCorrect ? (<div>
                <div>项目名称：{state.name}</div>
                <div>截止时间：{state.time}</div>
                <div><Button onClick={() => downloadPackage()}>下载压缩包</Button></div>
                <WhiteSpace/>
                <div>
                    <List renderHeader="未交同学名单">
                        {
                            state.unHandle.map(item => (
                                <List.Item multipleLine>
                                    {item.name}
                                    <Brief>{item.stuid}</Brief>
                                </List.Item>
                            ))
                        }
                    </List>
                </div>
            </div>) : <div>访问失败，可能是由于 s-key 错误。</div> }
        </div>
    )
};

export default Index;
